<template>
  <div class="app-container">
    <div class="conversation-header">
      <el-row>
        <el-col :span="24">
          <div class="conversation-title">
            <h2>{{ conversationTitle }}</h2>
            <div class="conversation-info">
              <span>用户ID: {{ userId }}</span>
              <span>会话ID: {{ conversationId }}</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-divider></el-divider>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="是否删除" prop="isDeleted">
        <el-select v-model="queryParams.isDeleted" placeholder="是否删除" clearable>
          <el-option
            v-for="dict in deleteOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-chat-line-round"
          size="mini"
          @click="handleChat"
          v-hasPermi="['chat:message:chat']"
        >继续对话</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
          v-hasPermi="['chat:message:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-back"
          size="mini"
          @click="handleGoBack"
        >返回列表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="消息ID" align="center" prop="id" />
      <el-table-column label="用户提问" align="center" prop="userQuestion" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleViewFullContent(scope.row.userQuestion, '用户提问')"
          >
            {{ truncateText(scope.row.userQuestion, 100) }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="AI回复" align="center" prop="aiResponse" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleViewFullContent(scope.row.aiResponse, 'AI回复')"
            v-if="scope.row.aiResponse"
          >
            {{ truncateText(scope.row.aiResponse, 100) }}
          </el-button>
          <span v-else style="color: #999">无回复</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间戳" align="center" prop="timestamp" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否删除" align="center" prop="isDeleted">
        <template slot-scope="scope">
          <dict-tag :options="deleteOptions" :value="scope.row.isDeleted"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isDeleted === 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['chat:message:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.isDeleted === 1"
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleRestore(scope.row)"
            v-hasPermi="['chat:message:restore']"
          >恢复</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看详细内容对话框 -->
    <el-dialog :title="contentDialogTitle" :visible.sync="contentDialogVisible" width="50%" append-to-body>
      <pre class="content-dialog-pre">{{ contentDialogContent }}</pre>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contentDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleCopyContent">复制内容</el-button>
      </div>
    </el-dialog>

    <!-- 继续对话弹窗 -->
    <el-dialog title="继续对话" :visible.sync="chatDialogVisible" width="60%" append-to-body>
      <div class="chat-messages-container">
        <div class="chat-message" v-for="(message, index) in chatMessages" :key="index">
          <div class="message-user" v-if="message.userQuestion">
            <div class="message-avatar user-avatar">用户</div>
            <div class="message-content">{{ message.userQuestion }}</div>
          </div>
          <div class="message-ai" v-if="message.aiResponse">
            <div class="message-avatar ai-avatar">AI</div>
            <div class="message-content">{{ message.aiResponse }}</div>
          </div>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="chat-input-container">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入您的问题..."
          v-model="newQuestion"
        ></el-input>
        <div class="chat-actions">
          <el-button @click="chatDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="sendMessage" :loading="sendingMessage">发送</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getConversationMessages, deleteMessage, restoreMessage } from "@/api/chat/message";
import { getConversation } from "@/api/chat/conversation";
import Clipboard from 'clipboard';

export default {
  name: "ConversationMessages",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      messageList: [],
      // 会话ID
      conversationId: null,
      // 会话标题
      conversationTitle: "",
      // 用户ID
      userId: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        conversationId: null,
        isDeleted: null
      },
      // 删除状态选项
      deleteOptions: [
        {
          value: "0",
          label: "未删除"
        },
        {
          value: "1",
          label: "已删除"
        }
      ],
      // 内容对话框可见性
      contentDialogVisible: false,
      // 内容对话框标题
      contentDialogTitle: "",
      // 内容对话框内容
      contentDialogContent: "",
      // 聊天对话框可见性
      chatDialogVisible: false,
      // 聊天记录
      chatMessages: [],
      // 新问题
      newQuestion: "",
      // 是否正在发送消息
      sendingMessage: false
    };
  },
  created() {
    // 从路由参数获取会话ID
    this.conversationId = this.$route.query.conversationId;
    this.conversationTitle = this.$route.query.title || "未命名对话";
    this.userId = this.$route.query.userId;
    
    if (!this.conversationId) {
      this.$message.error("未指定会话ID，请返回对话列表重新选择");
      this.handleGoBack();
      return;
    }

    // 设置查询参数
    this.queryParams.conversationId = this.conversationId;
    this.getList();
    this.getConversationDetail();
  },
  methods: {
    // 基于会话上下文的流式聊天API
    streamChatWithContext(question, conversationId) {
      return new EventSource(`/api/chat/stream/conversation/${conversationId}?question=${encodeURIComponent(question)}`);
    },
    /** 查询对话详情 */
    getConversationDetail() {
      if (this.conversationId) {
        getConversation(this.conversationId).then(response => {
          if (response.data) {
            this.conversationTitle = response.data.title;
            this.userId = response.data.userId;
          }
        });
      }
    },
    /** 查询消息列表 */
    getList() {
      this.loading = true;
      getConversationMessages(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        if (response.data && response.data.data) {
          this.messageList = response.data.data;
          this.total = response.data.total || 0;
        } else {
          this.messageList = [];
          this.total = 0;
        }
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.conversationId = this.conversationId;
      this.handleQuery();
    },
    /** 返回对话列表 */
    handleGoBack() {
      this.$router.push({ path: '/chat/conversation' });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const messageId = row.id;
      this.$modal.confirm('是否确认删除消息ID为"' + messageId + '"的记录？删除后用户将无法看到此消息。').then(function() {
        return deleteMessage(messageId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 恢复按钮操作 */
    handleRestore(row) {
      const messageId = row.id;
      this.$modal.confirm('是否确认恢复消息ID为"' + messageId + '"的记录？恢复后用户将可以看到此消息。').then(function() {
        return restoreMessage(messageId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("恢复成功");
      }).catch(() => {});
    },
    /** 批量删除按钮操作 */
    handleBatchDelete() {
      const messageIds = this.ids;
      this.$modal.confirm('是否确认批量删除所选的' + messageIds.length + '条消息？删除后用户将无法看到这些消息。').then(function() {
        return deleteMessage(messageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("批量删除成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 截断文本
    truncateText(text, maxLength) {
      if (!text) return '';
      return text.length > maxLength ? text.slice(0, maxLength) + '...' : text;
    },
    // 查看完整内容
    handleViewFullContent(content, title) {
      this.contentDialogTitle = title;
      this.contentDialogContent = content || '无内容';
      this.contentDialogVisible = true;
    },
    // 复制内容
    handleCopyContent() {
      const clipboard = new Clipboard('.dialog-footer .el-button--primary', {
        text: () => this.contentDialogContent
      });
      
      clipboard.on('success', e => {
        this.$message.success('内容已复制到剪贴板');
        clipboard.destroy();
      });
      
      clipboard.on('error', e => {
        this.$message.error('复制失败，请手动复制');
        clipboard.destroy();
      });
      
      clipboard.onClick({ currentTarget: document.querySelector('.dialog-footer .el-button--primary') });
    },
    // 继续对话
    handleChat() {
      // 获取会话的所有消息
      this.loading = true;
      const params = {
        conversationId: this.conversationId,
        pageNum: 1,
        pageSize: 100, // 获取较多记录用于对话
        isDeleted: 0 // 只获取未删除的记录
      };
      
      getConversationMessages(params).then(response => {
        if (response.data && response.data.data) {
          this.chatMessages = response.data.data;
        } else {
          this.chatMessages = [];
        }
        this.loading = false;
        this.chatDialogVisible = true;
      });
    },
    // 发送消息
    sendMessage() {
      if (!this.newQuestion.trim()) {
        this.$message.warning('请输入问题内容');
        return;
      }

      this.sendingMessage = true;
      
      // 创建一个事件源
      const eventSource = this.streamChatWithContext(this.newQuestion, this.conversationId);
      
      // 添加用户消息到聊天记录
      this.chatMessages.push({
        userQuestion: this.newQuestion,
        aiResponse: ''
      });
      
      // 最新消息的索引
      const newMessageIndex = this.chatMessages.length - 1;
      let aiResponse = '';
      
      // 处理服务器推送的事件
      eventSource.addEventListener('message', event => {
        if (event.data === "[DONE]") {
          // 响应完成，关闭事件源
          eventSource.close();
          this.sendingMessage = false;
          
          // 刷新消息列表
          this.getList();
        } else {
          // 累积AI回复内容
          aiResponse += event.data;
          this.chatMessages[newMessageIndex].aiResponse = aiResponse;
        }
      });
      
      eventSource.addEventListener('error', event => {
        this.sendingMessage = false;
        this.$message.error('发送消息失败，请重试');
        eventSource.close();
      });
      
      // 清空输入框
      this.newQuestion = '';
    }
  }
};
</script>

<style scoped>
.conversation-header {
  margin-bottom: 20px;
}

.conversation-title {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.conversation-title h2 {
  margin-bottom: 10px;
}

.conversation-info {
  color: #666;
  font-size: 14px;
}

.conversation-info span {
  margin-right: 20px;
}

.content-dialog-pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.chat-messages-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.chat-message {
  margin-bottom: 15px;
}

.message-user, .message-ai {
  display: flex;
  margin-bottom: 10px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: bold;
  margin-right: 10px;
  flex-shrink: 0;
}

.user-avatar {
  background-color: #409EFF;
}

.ai-avatar {
  background-color: #67C23A;
}

.message-content {
  background-color: #f4f4f5;
  padding: 10px 15px;
  border-radius: 8px;
  max-width: 80%;
  word-break: break-word;
}

.message-ai .message-content {
  background-color: #ecf5ff;
}

.chat-input-container {
  margin-top: 20px;
}

.chat-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style> 